// testeventengine.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include "EventEngine/Dispatcher.h"
#include "Common/Log.h"

#include "sumEvent.h"

#include <cstdint>
#include <memory>
#include <sstream>

using namespace NTrader;

volatile int64_t sum = 0;

class SumActor :public IActor
{
public:
	SumActor(size_t size) :IActor(size)
	{

	};
	~SumActor()
	{

	}

	void EventHandler(Event_t event) override
	{
		//BOOST_LOG_SEV(TraderLog::get(), severity_level::debug) << "timer";
		//std::cout << "timer" << std::endl;

		int64_t x;
		event->Get(x);
		sum += x;

		//std::stringstream ss;
		//ss << x;
		//TRADERLOG(ss.str())
	}
};

class TimerActor :public IActor
{
public:
	TimerActor(size_t size) :IActor(size)
	{

	};
	~TimerActor()
	{

	}

	void EventHandler(Event_t event) override
	{

		std::stringstream ss;
		ss << "timer sum :"  << sum;
		TRADERLOG(ss.str())
	}
};


int main()
{
	TRADERLOG("test bingin")

	Dispatcher::Actor_t t = std::make_shared<SumActor>(1024*4);
	Dispatcher::Actor_t time = std::make_shared<TimerActor>(1024);

	Dispatcher::Instance().RegisterHandler(EventType::EVENT_TEST,t);
	//Dispatcher::Instance().RegisterHandler(EventType::EVENT_TIMER, time);

	const int64_t iterationCount = 100 * 1000 * 1000;
	const uint32_t runCount = 5;

	int64_t expectedResult = 0;
	for (int64_t i = 0; i < iterationCount; i++)
	{
		expectedResult += i;
	}

	for (uint32_t run = 1; run <= runCount; ++run)
	{
		auto start = std::chrono::high_resolution_clock::now();

		for (int64_t i = 0; i < iterationCount; ++i)
		{
			Dispatcher::Event_t e = std::make_shared<SumEvent>();
			e->Set(i);
			Dispatcher::GlobalInstance().Post(e);
		}
		
		while (sum != expectedResult)
		{
			//TRADERLOG_INFO("in the circle");
		}

		const auto timeTaken = std::chrono::high_resolution_clock::now() - start;
		const auto timeTakenUS = std::chrono::duration_cast<std::chrono::microseconds>(timeTaken).count();

		std::stringstream ss;
		ss << "running: " << run 
			<< " sum: " << sum << "  " 
			<< iterationCount * 1000 * 1000 / timeTakenUS << " ops/s" <<std::endl;

		TRADERLOG(ss.str())

		sum = 0;
	}

	getchar();
    return 0;
}

